<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-collapse v-model="activeNames" accordion>
      <el-collapse-item 
        v-for="(item, index) in circleList" 
        :key="index"
        :name="index"
        :title="item.oneName"
      >
        <!-- 一级分类操作按钮 -->
        <div class="category-actions" slot="title">
          <span>{{ item.oneName }}</span>
          <el-button 
            type="primary" 
            size="mini" 
            icon="el-icon-plus"
            @click.stop="handleAdd(item)"
            style="margin-left: 10px;"
          >
            新增圈子
          </el-button>
        </div>

        <el-table 
          v-loading="loading" 
          :data="item.one" 
          style="width: 100%"
          :show-header="false"
        >
          <el-table-column width="80" align="center">
            <template slot-scope="scope">
              <div class="circle-avatar">
                <img 
                  :src="scope.row.twoImg" 
                  :alt="scope.row.twoName"
                  @error="handleImageError"
                />
              </div>
            </template>
          </el-table-column>
          
          <el-table-column>
            <template slot-scope="scope">
              <div class="circle-info">
                <h4 class="circle-name">{{ scope.row.twoName }}</h4>
                <p class="circle-heat">关注人数: {{ scope.row.heat }}</p>
              </div>
            </template>
          </el-table-column>

          <el-table-column width="240" align="center">
            <template slot-scope="scope">
              <el-button
                style="display:inline-block"
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(scope.row, item)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                style="display:inline-block"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row, item)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <!-- 空状态 -->
    <el-empty 
      v-if="circleList.length === 0 && !loading" 
      description="暂无圈子数据"
    >
    </el-empty>

    <!-- 隐藏的图片预览组件 -->
    <el-image
      v-if="form.twoImg"
      ref="previewImage"
      :src="form.twoImg"
      :preview-src-list="[form.twoImg]"
      style="display: none;"
    />

    <!-- 新增/编辑圈子弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="圈子名称" prop="twoName">
          <el-input 
            v-model="form.twoName" 
            placeholder="请输入圈子名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="圈子图片" prop="twoImg">
          <div class="image-upload-container">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              :on-error="handleImageUploadError"
              :disabled="false"
            >
              <img v-if="form.twoImg" :src="form.twoImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div v-if="form.twoImg" class="image-actions">
              <el-button 
                type="primary" 
                size="mini" 
                icon="el-icon-view"
                @click="previewImage"
              >
                预览
              </el-button>
              <el-button 
                type="danger" 
                size="mini" 
                icon="el-icon-delete"
                @click="deleteImage"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCircle, addCircle, updateCircle, deleteCircle } from "@/api/user/community";
import { getToken } from "@/utils/auth";

export default {
  name: "Community",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: false,
      // 圈子列表数据
      circleList: [],
      // 当前激活的折叠面板
      activeNames: [0],
      // 列信息
      columns: [
        { key: 0, label: `圈子名称`, visible: true },
        { key: 1, label: `关注人数`, visible: true },
        { key: 2, label: `操作`, visible: true }
      ],
      // 弹窗相关
      dialogVisible: false,
      dialogTitle: "",
      submitLoading: false,
      // 表单数据
      form: {
        type: "",
        oneId: "",
        twoId: "",
        twoName: "",
        twoImg: ""
      },
      // 表单验证规则
      rules: {
        twoName: [
          { required: true, message: "请输入圈子名称", trigger: "blur" },
          { min: 1, max: 50, message: "圈子名称长度在 1 到 50 个字符", trigger: "blur" }
        ],
        twoImg: [
          { required: true, message: "请上传圈子图片", trigger: "change" }
        ]
      },
      // 当前操作的一级分类
      currentCategory: null,
      // 图片上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询圈子列表 */
    getList() {
      this.loading = true;
      listCircle().then(response => {
        this.circleList = response.data || [];
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 图片加载错误处理 */
    handleImageError(event) {
      event.target.src = require('@/assets/images/profile.jpg');
    },
    /** 图片上传失败处理 */
    handleImageUploadError() {
      this.$modal.msgError("图片上传失败，请重试");
      this.$modal.closeLoading();
    },
    /** 图片上传成功回调 */
    handleImageSuccess(res, file) {
      if (res.code === 200) {
        this.form.twoImg = res.fileName;
        this.$modal.msgSuccess("图片上传成功");
        this.$modal.closeLoading();
      } else {
        this.$modal.msgError(res.msg || "图片上传失败");
        this.$modal.closeLoading();
      }
    },
    /** 图片上传前验证 */
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$modal.msgError('上传图片只能是 JPG/PNG/GIF 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$modal.msgError('上传图片大小不能超过 5MB!');
        return false;
      }
      this.$modal.loading("正在上传图片，请稍候...");
      return true;
    },
    /** 预览图片 */
    previewImage() {
      if (this.form.twoImg) {
        // 使用Element UI的Image组件进行预览
        this.$nextTick(() => {
          if (this.$refs.previewImage) {
            this.$refs.previewImage.clickHandler();
          }
        });
      }
    },
    /** 删除图片 */
    deleteImage() {
      this.$confirm('确定要删除当前图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.twoImg = '';
        this.$modal.msgSuccess('图片已删除');
      }).catch(() => {});
    },
    /** 新增圈子 */
    handleAdd(category) {
      this.dialogTitle = "新增圈子";
      this.dialogVisible = true;
      this.currentCategory = category;
      this.form = {
        type: "1",
        oneId: category.oneId || "1",
        twoId: "",
        twoName: "",
        twoImg: ""
      };
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    /** 编辑圈子 */
    handleEdit(row, category) {
      this.dialogTitle = "编辑圈子";
      this.dialogVisible = true;
      this.currentCategory = category;
      this.form = {
        type: "2",
        oneId: category.oneId || "1",
        twoId: row.twoId || "",
        twoName: row.twoName,
        twoImg: row.twoImg || ""
      };
      console.log(this.form)
      return
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    /** 删除圈子 */
    handleDelete(row, category) {
      this.$confirm(
        `确定要删除圈子"${row.twoName}"吗？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        const deleteData = {
          type: "3",
          oneId: category.oneId ,
          twoId: row.twoId || "",
          twoName: "",
          twoImg: ""
        };
        
        deleteCircle(deleteData).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        }).catch(() => {
          this.$modal.msgError("删除失败");
        });
      }).catch(() => {});
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          const submitData = { ...this.form };
          
          if (this.form.twoId) {
            // 编辑
            updateCircle(submitData).then(response => {
              this.$modal.msgSuccess("编辑成功");
              this.dialogVisible = false;
              this.getList();
            }).catch(() => {
              this.$modal.msgError("编辑失败");
            }).finally(() => {
              this.submitLoading = false;
            });
          } else {
            // 新增
            addCircle(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.dialogVisible = false;
              this.getList();
            }).catch(() => {
              this.$modal.msgError("新增失败");
            }).finally(() => {
              this.submitLoading = false;
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.circle-info {
  padding: 10px 0;
}

.circle-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.circle-heat {
  margin: 0;
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
}

.circle-heat::before {
  content: "👥";
  margin-right: 5px;
  font-size: 12px;
}

.category-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.el-collapse-item {
  margin-bottom: 15px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-collapse-item >>> .el-collapse-item__header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  font-size: 16px;
  padding: 15px 20px;
  border: none;
}

.el-collapse-item >>> .el-collapse-item__header:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.el-collapse-item >>> .el-collapse-item__content {
  padding: 20px;
  background-color: #fff;
  border: none;
}

.el-table {
  border: none;
  background-color: transparent;
}

.el-table >>> .el-table__body-wrapper {
  background-color: transparent;
}

.el-table >>> .el-table__body tr {
  background-color: transparent;
  transition: all 0.3s ease;
}

.el-table >>> .el-table__body tr:hover > td {
  background-color: #f8f9fa;
  transform: translateY(-2px);
}

.el-table td {
  border: none;
  padding: 15px 0;
  background-color: transparent;
}

.circle-avatar {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid #e4e7ed;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  margin: 0 auto;
}

.circle-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

.circle-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 7px;
}

.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.mb8 {
  margin-bottom: 20px;
}

/* 空状态样式 */
.el-empty {
  background-color: white;
  border-radius: 8px;
  padding: 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 操作按钮样式 */
.el-button + .el-button {
  margin-left: 8px;
}

/* 图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.image-upload-container {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  gap: 15px;
}

.image-actions {
  display: flex;
  flex-direction: row;
  gap: 8px;
}

.avatar-uploader .el-upload:disabled {
  cursor: not-allowed;
}

.avatar-uploader .el-upload:disabled:hover {
  border-color: #d9d9d9;
}

/* 图片预览弹窗样式 */
.image-preview-dialog {
  .el-message-box__content {
    text-align: center;
    padding: 20px;
  }
  
  .el-image {
    border-radius: 8px;
    overflow: hidden;
  }
}
</style>
